package sd.qd.xiaoming.coffeedesk.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import sd.qd.xiaoming.coffeedesk.entity.CdDirectory;
import sd.qd.xiaoming.coffeedesk.entity.CdFile;
import sd.qd.xiaoming.coffeedesk.service.CdDirectoryService;
import sd.qd.xiaoming.coffeedesk.service.CdFileService;
import sd.qd.xiaoming.coffeedesk.support.FileSupport;

import com.mysql.jdbc.StringUtils;

@Controller
@RequestMapping("/file")
public class CdFileController {

    @Autowired
    private CdFileService cdFileService;
    @Autowired
    private CdDirectoryService cdDirectoryService;
    @Autowired
    private FileSupport fileSupport;


    @ResponseBody
    @RequestMapping("/delete_file/{id}")
    public Object deleteFile(@PathVariable("id") final Long id) {
        Map<String, Object> result = new HashMap<String, Object>();
        this.cdFileService.deleteById(id);
        result.put("success", true);
        return result;
    }

    @ResponseBody
    @RequestMapping("/down_file/{id}")
    public Object downFile(@PathVariable("id") final Long id,
            final HttpServletResponse response) {
        try {
            CdFile file = this.cdFileService.findById(id);
            String filename = file.getName();
            byte[] fileBytes = this.fileSupport.getBytes(file.getCode());

            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename="
                    + new String(filename.getBytes("utf-8"), "ISO-8859-1"));
            response.addHeader("Content-Length", "" + fileBytes.length);
            OutputStream toClient = new BufferedOutputStream(
                    response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(fileBytes);
            toClient.flush();
            toClient.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    @ResponseBody
    @RequestMapping("/get_file_list")
    public Object getFileList(
            @RequestParam(value = "directory_id", required = false) Long did) {
        if (null == did) {
            did = this.cdDirectoryService.findByPid(null).get(0).getId();
        }
        List<CdDirectory> dList = this.cdDirectoryService.findByPid(did);
        for (CdDirectory d : dList) {
            d.setChildren(null);
            d.setParent(null);
            d.setFiles(null);
        }
        List<CdFile> list = this.cdFileService.findByDirectoryId(did);
        for (CdFile f : list) {
            if (StringUtils.isNullOrEmpty(f.getCode())) {
                f.setCode("noCode");
            }
            f.setDirectory(null);
        }
        List<Object> result = new ArrayList<Object>();
        result.addAll(dList);
        result.addAll(list);
        return result;
    }

    @ResponseBody
    @RequestMapping("/upload_file")
    public Object uploadFile(@RequestParam("file") final MultipartFile file,
            @RequestParam("directory_id") final Long did) {
        String fileCode=UUID.randomUUID().toString();
        try {
            this.fileSupport.save(fileCode, file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }


        CdFile cdfile=new CdFile();
        cdfile.setAccessCount(0L);
        cdfile.setCode(fileCode);
        cdfile.setDirectory(this.cdDirectoryService.findById(did));
        Date now = new Date();
        cdfile.setEditTime(now);
        cdfile.setLastAccessTime(now);
        cdfile.setName(file.getOriginalFilename());
        cdfile.setSize(file.getSize());
        //TODO 文件摘要
        cdfile.setSummary(file.getOriginalFilename());
        String fileName=file.getOriginalFilename();
        int index = fileName.lastIndexOf(".");
        if(-1==index){
            cdfile.setType(" - - ");
        } else {
            cdfile.setType(fileName.substring(index + 1));
        }
        cdfile.setUpTime(now);
        this.cdFileService.save(cdfile);
        return "";
    }

}
